package cn.besbing.server.controllers.actions;


import cn.besbing.model.entities.primary.DbFiles;
import cn.besbing.model.entities.primary.DbFilesExample;
import cn.besbing.server.service.primary.CustomerSqlServiceImpl;
import cn.besbing.server.service.primary.DbFilesServiceImpl;
import cn.besbing.server.utils.DataloaderLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@Controller
public class FilesDownloadControllers implements ServletContextAware {

    @Autowired
    private CustomerSqlServiceImpl customerSqlService;

    @Autowired
    private DbFilesServiceImpl dbFilesService;

    private ServletContext servletContext;

    private DbFiles dbFiles = null;

    private DbFilesExample dbFilesExample = null;


    @RequestMapping(value = "/preview/ReportServletController")
    public void previewReportServletController(@RequestParam("param") String param, HttpServletRequest request, HttpServletResponse response){
        String taskidAndReportypeArr[] = param.split(":");
        DataloaderLogger.getDataloaderLogger().info("{}开始校验单据信息:{}......",this.getClass().getName(),param);
        //开始在db_files中查询最新的report
        String findLastReportFromDbFilesSql = " select file_name,original_path,original_name,file_size,changed_on ";
        findLastReportFromDbFilesSql += " from db_files where description = '" + taskidAndReportypeArr[0].trim() + "' ";
        findLastReportFromDbFilesSql += " group by file_name,original_path,original_name,file_size,changed_on ";
        findLastReportFromDbFilesSql += " having changed_on = ( select max(df.changed_on) from db_files df ";
        findLastReportFromDbFilesSql += " where df.description = '" + taskidAndReportypeArr[0].trim() + "' ) ";
        List<Map<String,Object>> lastReportFromDbFilesList = customerSqlService.selectList(findLastReportFromDbFilesSql);
        Map<String,Object> conditionMap = lastReportFromDbFilesList.get(0);
        DbFilesExample dbFilesExample = new DbFilesExample();
        DbFilesExample.Criteria criteria = dbFilesExample.createCriteria();
        criteria.andFileNameEqualTo(conditionMap.get("file_name".toUpperCase()).toString());
        criteria.andOriginalPathEqualTo(conditionMap.get("original_path".toUpperCase()).toString());
        criteria.andOriginalNameEqualTo(conditionMap.get("original_name".toUpperCase()).toString());
        criteria.andFileSizeEqualTo(Long.valueOf(conditionMap.get("file_size".toUpperCase()).toString()));
        List<DbFiles> list = dbFilesService.selectByExampleWithBLOBs(dbFilesExample);
        if (list.size() > 0)
            dbFiles = list.get(0);
        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        //response.setContentType("application/pdf");
        byte[] buffer = null;
        //2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
        response.setHeader("Content-Disposition", dbFiles.getFileName());
        try{
            ServletOutputStream out;
            InputStream inputStream = new ByteArrayInputStream(dbFiles.getFileContents());
            //3.通过response获取ServletOutputStream对象(out)
            out = response.getOutputStream();

            int b = 0;
            buffer = new byte[1024];
            while ((b=inputStream.read(buffer))!=-1){
                //4.写到输出流(out)中
                out.write(buffer,0,b);
            }
            inputStream.close();
            out.close();
            out.flush();
        }catch(IOException e){
            e.printStackTrace();
        }
        //return buffer;

    }

    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

}
